/**
 * 一次性定时器hook
 * @param lazy false为立即执行一次
 * @returns
 */

export function useTimeOut() {
  const timer = ref<number | undefined>(undefined)

  function setTimer(data: number) {
    timer.value = data
  }

  function startTimeout(cb: () => void, interval = 300, lazy?: boolean) {
    closeTimeout()

    const timerout = setTimeout(cb, interval)

    setTimer(timerout as unknown as number)

    if (lazy === false) {
      cb()
    }
  }
  function closeTimeout() {
    timer.value && clearTimeout(timer.value)

    timer.value = undefined
  }

  onUnmounted(() => {
    closeTimeout()
  })

  return {
    startTimeout,
    closeTimeout
  }
}

/**
 * 循环定时器hook
 * @returns
 */
export function useInterval() {
  const timer = ref<number | undefined>(undefined)

  function setTimer(data: number) {
    timer.value = data
    console.log(timer.value)
  }

  /**
   *
   * @param cb 执行函数体
   * @param interval 间隔时间
   * @param lazy false为立即执行一次
   */
  function startInterval(cb: () => void, interval = 300, lazy?: boolean) {
    closeInterval()
    const time = setInterval(cb, interval)

    lazy === false && cb()
    setTimer(time as unknown as number)
  }

  function closeInterval() {
    timer.value && clearInterval(timer.value)
    timer.value = undefined
  }

  onUnmounted(() => {
    console.log('interval onUnmounted')
    closeInterval()
  })
  onDeactivated(() => {
    console.log('interval onDeactivated')
    closeInterval()
  })

  return {
    startInterval,
    closeInterval
  }
}
